package com.czm.art_light.service.impl;

import com.czm.art_light.annotation.DistributedLock;
import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.constant.CommonConsts;
import com.czm.art_light.entity.ArtFeedbackType;
import com.czm.art_light.entity.ArtUserFeedback;
import com.czm.art_light.exception.BusinessException;
import com.czm.art_light.exception.CommonExceptionHandler;
import com.czm.art_light.mapper.ArtFeedbackTypeMapper;
import com.czm.art_light.mapper.ArtUserFeedbackMapper;
import com.czm.art_light.param.request.ArtUserFeedbackReqDto;
import com.czm.art_light.param.response.ArtUserFeedbackRespDto;
import com.czm.art_light.service.ArtUserFeedbackService;
import com.czm.art_light.util.UserHolderUtility;
import com.czm.art_light.util.XSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 反馈内容信息 服务类
 */
@Service
public class ArtUserFeedbackServiceImpl implements ArtUserFeedbackService {
    @Autowired
    private ArtUserFeedbackMapper artUserFeedbackMapper;

    @Autowired
    private ArtFeedbackTypeMapper artFeedbackTypeMapper;


    /**
     * 添加反馈的内容
     */
    @DistributedLock(
            prefix = "addFeedback",
            lockKey = "#artUserFeedbackReqDto.typeId"
    )
    @Override
    public void addFeedback(ArtUserFeedbackReqDto artUserFeedbackReqDto) {
        ArtUserFeedback artUserFeedback = new ArtUserFeedback();
        // 获取当前用户的ID
        artUserFeedback.setUserId(UserHolderUtility.getUserId());
        // 反馈类型ID（关联反馈类型表）
        artUserFeedback.setTypeId(artUserFeedbackReqDto.getTypeId());

        // 过滤XSS
        // 用户联系方式（邮箱、电话、微信等）
        String contactInfo = XSSUtil.cleanXSS(artUserFeedbackReqDto.getContactInfo());
        if (contactInfo == null || contactInfo.isEmpty()) {
            throw new BusinessException(ArtErrorCodeEnum.INVALID_CONTACT_INFO);
        }
        artUserFeedback.setContactInfo(contactInfo);

        // 反馈内容
        String content = XSSUtil.cleanXSS(artUserFeedbackReqDto.getContent());
        if (content == null || content.isEmpty()) {
            throw new BusinessException(ArtErrorCodeEnum.INVALID_FEEDBACK_CONTENT);
        }
        artUserFeedback.setContent(content);

        // 反馈图片URL集合，多个图片用逗号隔开
        // 反馈图片链接（JSON 数组格式）
        if (!XSSUtil.isValidImageUrls(artUserFeedbackReqDto.getImageUrls())) {
            throw new BusinessException(ArtErrorCodeEnum.INVALID_FEEDBACK_IMAGE_LINKS);
        }
        artUserFeedback.setImageUrls(artUserFeedbackReqDto.getImageUrls());
        // 反馈状态：未处理
        artUserFeedback.setStatus(CommonConsts.FeedbackStatusEnum.UNPROCESSED.getCode());

        int i = artUserFeedbackMapper.addFeedback(artUserFeedback);
        if (i <= 0) {
            // 反馈添加失败，抛出自定义异常
            throw new BusinessException(ArtErrorCodeEnum.FEEDBACK_ADD_ERROR);
        }
    }

    /**
     * 获取当前用户的所有反馈
     */
    @Override
    public List<ArtUserFeedbackRespDto> getFeedbackByUserId() {
        List<ArtUserFeedback> artUserFeedbacks = artUserFeedbackMapper.selectByUserId(UserHolderUtility.getUserId());
        if (artUserFeedbacks.isEmpty()) {
            return List.of();
        }
        List<ArtUserFeedbackRespDto> artUserFeedbackRespDtos = new ArrayList<>();
        for (ArtUserFeedback artUserFeedback : artUserFeedbacks) {
            artUserFeedbackRespDtos.add(ArtUserFeedbackRespDto.builder()
                    //反馈记录唯一标识
                    .id(artUserFeedback.getId())
                    //反馈类型名字
                    .typeName(artFeedbackTypeMapper.getFeedbackTypeContentById(artUserFeedback.getTypeId()).getTypeName())
                    //用户联系方式（邮箱、电话、微信等）
                    .contactInfo(artUserFeedback.getContactInfo())
                    //反馈内容
                    .content(artUserFeedback.getContent())
                    //反馈图片链接（JSON 数组格式）
                    .imageUrls(artUserFeedback.getImageUrls())
                    //反馈状态（0: 未处理, 1: 处理中, 2: 已处理）
                    .status(artUserFeedback.getStatus())
                    //创建时间
                    .createdAt(artUserFeedback.getCreatedAt())
                    .build());
        }
        return artUserFeedbackRespDtos;
    }
}
